package com.neusoft.nep.admin.controller;

import com.neusoft.nep.admin.entity.ProvinceStatData;
import com.neusoft.nep.admin.entity.AqiData; // Import AqiData
import com.neusoft.nep.common.AqiDataFileUtil; // Import file utility

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProvinceAdminViewController {

    @FXML
    private TableView<ProvinceStatData> statTable;
    @FXML
    private TableColumn<ProvinceStatData, String> provinceIdColumn;
    @FXML
    private TableColumn<ProvinceStatData, String> provinceShortColumn;
    @FXML
    private TableColumn<ProvinceStatData, String> provinceNameColumn;
    @FXML
    private TableColumn<ProvinceStatData, Integer> so2ExcessColumn;
    @FXML
    private TableColumn<ProvinceStatData, Integer> coExcessColumn;
    @FXML
    private TableColumn<ProvinceStatData, Integer> pm25ExcessColumn;
    @FXML
    private TableColumn<ProvinceStatData, Integer> aqiExcessColumn;

    @FXML
    public void initialize() {
        provinceIdColumn.setCellValueFactory(new PropertyValueFactory<>("provinceId"));
        provinceShortColumn.setCellValueFactory(new PropertyValueFactory<>("provinceShort"));
        provinceNameColumn.setCellValueFactory(new PropertyValueFactory<>("provinceName"));
        so2ExcessColumn.setCellValueFactory(new PropertyValueFactory<>("so2Excess"));
        coExcessColumn.setCellValueFactory(new PropertyValueFactory<>("coExcess"));
        pm25ExcessColumn.setCellValueFactory(new PropertyValueFactory<>("pm25Excess"));
        aqiExcessColumn.setCellValueFactory(new PropertyValueFactory<>("aqiExcess"));

        // Replace mock data generation with actual data loading and calculation
        statTable.setItems(loadAndCalculateProvinceStats());
    }

    // Helper method to determine if a pollution level is "excessive"
    // This logic should be consistent with how 'excess' is defined in other parts of your app
    private boolean isExcessivePollution(String level) {
        if (level == null || level.isEmpty()) {
            return false;
        }
        switch (level) {
            case "优":
            case "良":
                return false;
            case "轻度污染":
            case "中度污染":
            case "重度污染":
            case "严重污染":
                return true;
            default:
                return false;
        }
    }


    private ObservableList<ProvinceStatData> loadAndCalculateProvinceStats() {
        // A temporary map to aggregate statistics for each province
        // Key: Province Name (String), Value: ProvinceStatData object (to update counts)
        Map<String, ProvinceStatData> provinceStatsMap = new HashMap<>();

        // Assuming AqiDataFileUtil reads from "fankui3.txt" and returns List<AqiData>
        List<AqiData> allAqiData = AqiDataFileUtil.readAqiDataFromFile();

        if (allAqiData.isEmpty()) {
            System.out.println("文件 fankui3.txt 中没有AQI数据可供统计省份。");
            return FXCollections.observableArrayList(); // Return empty list if no data
        }


        Map<String, String> provinceNameToIdMap = new HashMap<>();
        Map<String, String> provinceNameToShortMap = new HashMap<>();

        provinceNameToIdMap.put("湖南省", "1001");
        provinceNameToShortMap.put("湖南省", "湘");
        provinceNameToIdMap.put("辽宁省", "1002");
        provinceNameToShortMap.put("辽宁省", "辽");
        provinceNameToIdMap.put("山西省", "1003");
        provinceNameToShortMap.put("山西省", "晋");
        // Add more provinces as needed
        provinceNameToIdMap.put("北京市", "1004");
        provinceNameToShortMap.put("北京市", "京");
        provinceNameToIdMap.put("上海市", "1005");
        provinceNameToShortMap.put("上海市", "沪");


        for (AqiData data : allAqiData) {
            String provinceName = data.getProvince(); // Get province name from AqiData
            String level = data.getLevel();          // Get AQI level

            if (provinceName == null || provinceName.isEmpty()) {
                System.err.println("跳过缺少省份信息的数据: " + data.getId());
                continue;
            }

            // Get or create ProvinceStatData for this province
            ProvinceStatData statData = provinceStatsMap.computeIfAbsent(provinceName, k -> {
                String id = provinceNameToIdMap.getOrDefault(k, "N/A");
                String shortName = provinceNameToShortMap.getOrDefault(k, "N/A");
                return new ProvinceStatData(id, shortName, k, 0, 0, 0, 0);
            });

            // If the pollution is excessive, increment all excess counts for this province
            if (isExcessivePollution(level)) {
                statData.setSo2Excess(statData.getSo2Excess() + 1);
                statData.setCoExcess(statData.getCoExcess() + 1);
                statData.setPm25Excess(statData.getPm25Excess() + 1);
                statData.setAqiExcess(statData.getAqiExcess() + 1);
            }
        }

        ObservableList<ProvinceStatData> resultList = FXCollections.observableArrayList();
        resultList.addAll(provinceStatsMap.values());

        // Sort the list by province name for better readability
        resultList.sort(Comparator.comparing(ProvinceStatData::getProvinceName));

        System.out.println("省份统计数据已加载并计算完成。共统计到 " + resultList.size() + " 个省份的数据。");
        return resultList;
    }

    @FXML
    public void onBackButtonClick() {
        Stage stage = (Stage) statTable.getScene().getWindow();
        stage.hide();
    }
}